package com.moleq.logic;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import android.content.Context;

import com.moleq.device.DeviceManager;
import com.moleq.dialog.MessageBox;
import com.moleq.enums.ItemType;
import com.moleq.enums.PaymentType;
import com.moleq.enums.TransactionStatus;
import com.moleq.enums.TransactionType;
import com.moleq.itemsetting.tools.MGCreateFiles;
import com.moleq.models.CouponSetting;
import com.moleq.models.ItemDiscountSetting;
import com.moleq.models.FreeFuncRpt;
import com.moleq.models.GlobalInfo;
import com.moleq.models.ItemSales;
import com.moleq.models.PosEJ;
import com.moleq.models.PosSetting;
import com.moleq.models.PosTrns;
import com.moleq.models.Receipt;
import com.moleq.models.SaleListItem;
import com.moleq.models.TaxSetting;
import com.moleq.models.PosTender;
import com.moleq.service.PosSettingService;
import com.moleq.service.ServiceManager;
import com.moleq.test.SaleListView;
import com.moleq.util.BigDecmialTool;
import com.moleq.util.MoleQUtil;
import com.moleq.util.StringUtils;

public class TransactionManager {

	private static TransactionManager instance;
	// private PosSetting mPosSetting;
	// private int mStation;
	private List<TaxSetting> mTaxSettings;
	public int mTaxExempat = -1;
	private String BirthdayDate = "";
	public List<PosTender> tenderList = new ArrayList<PosTender>();
	public int Age = -1;
	public String trnDate;
	public TransactionType TransType;
	public SaleList mSaleListItems = new SaleList();
	public TransactionStatus status;
	public int manualTare = 0;
	public int TransactionNo;
	public String TransDntType = ""; // transaction discount type
	public double TransDntValue = 0; 
	private CouponSetting mCouponSetting;
	public String managerID;		// manager ID
	public String mTransType = "";
	public Date dDoneDate = null;
	public int shiftNum = -1;
	public boolean shiftFs = false;
	public boolean needToApproval = false;
	
	public boolean mLoadPendingItemMode = false;
	
	public double exemptTax1able = 0;
	public double exemptTax2able = 0;
	public double exemptTax3able = 0;
	public double exemptTax4able = 0;
	public double exemptTax5able = 0;
	public double exemptTax6able = 0;
	
	public int refundCount = 0;	//refund count
	public double CVVWicPrice = 0;
	public boolean isReprint = false;
	public String Rounding_flag = "";
	public double Rounding = 0;
	
	public static TransactionManager getInstance() {
		if (instance == null) {
			instance = new TransactionManager();

		}
		return instance;
	}

//	public void setManualTaxExempat(int statue) {
//		mTaxExempat = statue;
//		this.mSaleListItems.announceCartChanges();
//	}

	public void setTaxSetting(List<TaxSetting> list) {
		mTaxSettings = list;
	}

	public List<TaxSetting> getTaxSetting() {
		return mTaxSettings;
	}
	
	public TaxSetting getTaxSettingByNo(int tax_no){
		TaxSetting setting = null;
		
		for (int i = 0; i < mTaxSettings.size(); i++) {
			setting = mTaxSettings.get(i);
			if(mTaxSettings.get(i).getTx_no() == tax_no){
				setting = mTaxSettings.get(i);
				break;
			}
		}
		
		return setting;
	}
	
	public double calcTax(double totalPrice,TaxSetting setting){
		double result = 0;
		//tax绝对值
//		double tampPrice = Math.abs(totalPrice);
		
		if (setting != null && totalPrice >= setting.getTx_start_amt()) {
				result = totalPrice * setting.getTx_rate();
				result = BigDecmialTool.round(result, 2, setting.getTx_plus_round());
		}
		
		return result;
	}
	
	public double calcRefundTax(double totalPrice,TaxSetting setting){
		double result = 0;
		
		if (setting != null) {
				result = totalPrice * setting.getTx_rate();
				result = BigDecmialTool.round(result, 2, setting.getTx_plus_round() * -1);
		}
		
		return result;
	}
	
	private double getTax() {
		double result = 0;
		double taxable1 = 0, taxa1 = 0;
		double taxable2 = 0, taxa2 = 0;
		double taxable3 = 0, taxa3 = 0;
		double taxable4 = 0, taxa4 = 0;
		double taxable5 = 0, taxa5 = 0;
		double taxable6 = 0, taxa6 = 0;
		
		//Refund Transaction need to calc Tax
//		if (MoleQUtil.getTransType(TransType).equals("R")) {
//			return result;
//		}

		for (int i = 0; i < mSaleListItems.getItemCount(); i++) {
			SaleListItem item = mSaleListItems.getItem(i);
			double price = item.getPrice();
			if (!item.getNodiscount() ) {

				if (TransDntType.equals("P")) {
					price = price * (1 - TransDntValue * 0.01);
				} else if (TransDntType.equals("A")) {
					// //
				}
			}

			if (!item.isRefund()) {
				if (item.getTax1())
					taxable1 += price;
				if (item.getTax2())
					taxable2 += price;
				if (item.getTax3())
					taxable3 += price;
				if (item.getTax4())
					taxable4 += price;
				if (item.getTax5())
					taxable5 += price;
				if (item.getTax6())
					taxable6 += price;
			}
		}

		result += calcTax(taxable1, getTaxSettingByNo(1));
		result += calcTax(taxable2, getTaxSettingByNo(2));
		result += calcTax(taxable3, getTaxSettingByNo(3));
		result += calcTax(taxable4, getTaxSettingByNo(4));
		result += calcTax(taxable5, getTaxSettingByNo(5));
		result += calcTax(taxable6, getTaxSettingByNo(6));
		
		result += this.getRefundTax();
		return result;
	}
	
	private double getRefundTax() {
		double result = 0;
		double taxable1 = 0, taxa1 = 0;
		double taxable2 = 0, taxa2 = 0;
		double taxable3 = 0, taxa3 = 0;
		double taxable4 = 0, taxa4 = 0;
		double taxable5 = 0, taxa5 = 0;
		double taxable6 = 0, taxa6 = 0;

		for (int i = 0; i < mSaleListItems.getItemCount(); i++) {
			SaleListItem item = mSaleListItems.getItem(i);
			double price = item.getPrice();
			if (!item.getNodiscount() ) {

				if (TransDntType.equals("P")) {
					price = price * (1 - TransDntValue * 0.01);
				} else if (TransDntType.equals("A")) {
					// //
				}
			}

			if (item.isRefund()) {
				if (item.getTax1())
					taxable1 += price;
				if (item.getTax2())
					taxable2 += price;
				if (item.getTax3())
					taxable3 += price;
				if (item.getTax4())
					taxable4 += price;
				if (item.getTax5())
					taxable5 += price;
				if (item.getTax6())
					taxable6 += price;
			}
		}

		result += calcRefundTax(taxable1, getTaxSettingByNo(1));
		result += calcRefundTax(taxable2, getTaxSettingByNo(2));
		result += calcRefundTax(taxable3, getTaxSettingByNo(3));
		result += calcRefundTax(taxable4, getTaxSettingByNo(4));
		result += calcRefundTax(taxable5, getTaxSettingByNo(5));
		result += calcRefundTax(taxable6, getTaxSettingByNo(6));
		return result;
	}
	
	private double getTaxExempatByIllinois(){
		double result = 0;
		double taxable1 = 0;
		double taxable2 = 0;
		double taxable3 = 0;
		double taxable4 = 0;
		double taxable5 = 0;
		double taxable6 = 0;

		for (int i = 0; i < mSaleListItems.getItemCount(); i++) {
			SaleListItem item = mSaleListItems.getItem(i);
			double price = item.getFoodstampPrice();
			if (!item.getNodiscount() ) {

				if (TransDntType.equals("P")) {
					price = price * (1 - TransDntValue * 0.01);
				} else if (TransDntType.equals("A")) {
					// //
				}
			}
			if (item.getFoodstamp()) {
				if (item.getTax1())
					taxable1 += price;
				if (item.getTax2())
					taxable2 += price;
				if (item.getTax3())
					taxable3 += price;
				if (item.getTax4())
					taxable4 += price;
				if (item.getTax5())
					taxable5 += price;
				if (item.getTax6())
					taxable6 += price;
			}

		}

		result += calcTax(taxable1, getTaxSettingByNo(1));
		result += calcTax(taxable2, getTaxSettingByNo(2));
		result += calcTax(taxable3, getTaxSettingByNo(3));
		result += calcTax(taxable4, getTaxSettingByNo(4));
		result += calcTax(taxable5, getTaxSettingByNo(5));
		result += calcTax(taxable6, getTaxSettingByNo(6));
		return result;
	}

	private double getTaxExempat() {
		double result = 0;
		double taxable1 = 0, taxa1 = 0;
		double taxable2 = 0, taxa2 = 0;
		double taxable3 = 0, taxa3 = 0;
		double taxable4 = 0, taxa4 = 0;
		double taxable5 = 0, taxa5 = 0;
		double taxable6 = 0, taxa6 = 0;

		for (int i = 0; i < mSaleListItems.getItemCount(); i++) {
			SaleListItem item = mSaleListItems.getItem(i);
			double price = item.getPrice();
			if (!item.getNodiscount() ) {

				if (TransDntType.equals("P")) {
					price = price * (1 - TransDntValue * 0.01);
				} else if (TransDntType.equals("A")) {
					// //
				}
			}
			if (item.getFoodstamp()) {
				if (item.getTax1())
					taxable1 += price;
				if (item.getTax2())
					taxable2 += price;
				if (item.getTax3())
					taxable3 += price;
				if (item.getTax4())
					taxable4 += price;
				if (item.getTax5())
					taxable5 += price;
				if (item.getTax6())
					taxable6 += price;
			}

		}

		result += calcTax(taxable1, getTaxSettingByNo(1));
		result += calcTax(taxable2, getTaxSettingByNo(2));
		result += calcTax(taxable3, getTaxSettingByNo(3));
		result += calcTax(taxable4, getTaxSettingByNo(4));
		result += calcTax(taxable5, getTaxSettingByNo(5));
		result += calcTax(taxable6, getTaxSettingByNo(6));
		return result;
	}

	public void Reset() {
		TransDntType = "";
		TransDntValue = 0;
		CVVWicPrice = 0;	
		
		mCouponSetting = null;

		if (mSaleListItems == null) {
			mSaleListItems = new SaleList();
		}

		mSaleListItems.clear();

		if (this.tenderList == null) {
			tenderList = new ArrayList<PosTender>();
		}
		tenderList.clear();

		TransType = TransactionType.SALE;
		mTaxExempat = -1;
		status = TransactionStatus.CLOSED;
		setBirthdayDate("");
		Age = -1;
		// mSaleListItems = new SaleList(mShareContext);
		trnDate = MoleQUtil.getCurrentDate();
		manualTare = 0;
		shiftNum = -1;
		shiftFs = false;
		managerID = "";
		exemptTax1able = 0;
		exemptTax2able = 0;
		exemptTax3able = 0;
	    exemptTax4able = 0;
		exemptTax5able = 0;
		exemptTax6able = 0;
		needToApproval = false;	
		mLoadPendingItemMode = false;
		
		refundCount = 0;	// refund count
		isReprint = false;
		
		Rounding_flag = "";
		Rounding = 0;
		
		paymentReset();
		this.TransactionNo = generateID();
		GlobalInfo.getInstance().useFuntionsList.clear();
	}

	private int generateID() {

		return ServiceManager.getInstance().mPosTrnsService.getMaxNo() + 1;
	}

	public void pay(double paid, PaymentType type, String authNum) {
		if (paid > 0) {
			PosTender tender = new PosTender();
			tender.setPt_seq_no(tenderList.size() + 1);
			tender.setPt_tender(BigDecmialTool.round(paid, 2));
			tender.paymentType = type;
			tender.setPt_Auth(authNum);
			tenderList.add(tender);
		}
	}

	public void addTender(PosTender tender) {
		double price = 0;
		if (tenderList == null) {
			tenderList = new ArrayList<PosTender>();
		}
		tenderList.add(tender);
		if(GlobalInfo.getInstance().CurrentFreeFuncID == FreeFuncRpt.FF_CASH ){
			if (tender.getPt_tender() <= getChange()) {
				price = tender.getPt_tender();
			}else{
				price = tender.getPt_tender() - getChange();
			}
		}else{
			price =tender.getPt_tender();
		}
		GlobalInfo.getInstance().useFuntionsList.add(GlobalInfo.getInstance().CurrentFreeFuncID);
		if (MoleQUtil.getTransType(TransType).equals("R")) {
			price = price * (-1);
		}
		SaveFreeFuncRpt(GlobalInfo.getInstance().CurrentFreeFuncID, 1, price);
		
		tender.setPt_due(getDue());
		tender.setPt_change(getChange());
//		PosTender posTender = new PosTender();
//		posTender.setPt_store_id(GlobalInfo.getInstance().storeNo);
//		posTender.setPt_station(GlobalInfo.getInstance().stationNo);
//		posTender.setPt_date(trnDate);
	}
	
	public void setFoodStampPrice(double foodstamppay){
		
		double foodStampPrice = 0;
		foodStampPrice = foodstamppay;
		SaleListItem saleitem = null;
		for (int i = 0; i < mSaleListItems.mSaleItems.size(); i++) {
			if (foodStampPrice <= 0) {
				break;
			}
			saleitem = mSaleListItems.mSaleItems.get(i);
			ItemType type = saleitem.getItemType();
			if (type == ItemType.DISCOUNT_AMOUNT || type == ItemType.DISCOUNT_PERECENT || type == ItemType.LIMITED_QTY_PRICE_FIX || type == ItemType.PACKAGE_PRICE_FIX || type == ItemType.BOTTLE_DEPOSIT || type == ItemType.ENVIRONMENTAL_FEES || type == ItemType.ITEM_DISCOUNT_AMOUNT || type == ItemType.ITEM_DISCOUNT_PERECENT || type == ItemType.DISCOUNT_LINK) {

			} else if (saleitem.getFoodstamp() && saleitem.isTaxable() && saleitem.getFoodstampPrice() < saleitem.getPrice()) {
				double currentPrice = mSaleListItems.getRealPrice(saleitem);
				double tempPrice = foodStampPrice - currentPrice;
				if (tempPrice >= 0) {
					saleitem.setFoodstampPrice(saleitem.getFoodstampPrice() + currentPrice);
				} else {
					saleitem.setFoodstampPrice(saleitem.getFoodstampPrice() + foodStampPrice);
				}
				foodStampPrice = tempPrice;
			}
		}
	}

	public void paymentReset() {

		if (tenderList == null) {
			tenderList = new ArrayList<PosTender>();
		}
		tenderList.clear();
	}

	public int getCvvTender(){
		int tenderidx = -1;
		for (int i = 0; i < tenderList.size(); i++) {
			if (tenderList.get(i).paymentType == PaymentType.CVV) {
				return i;
			}
		}
		return tenderidx;
	}
	
	public double getTenderAmount(PaymentType type) {
		double amount = 0;
		for (int i = 0; i < tenderList.size(); i++) {
			if (tenderList.get(i).paymentType == type) {
				amount += tenderList.get(i).getPt_tender();
			}
		}
		
		return BigDecmialTool.round(amount, 2);
	}

	// 鏈敓鏂ゆ嫹閿熸枻鎷烽敓锟�	
	public double getDue() {
		double due = BigDecmialTool.sub(getAmountPayable(), getAmountOfPaidUp());
		return BigDecmialTool.round(due, 2);
	}

	// 鏈敓鏂ゆ嫹foodstamp
	public double getDueFoodstamp() {

		return BigDecmialTool.round(getFoodstamp() - getFoodstampOfPaidUp(), 2);
	}

	// 閿熺獤闈╂嫹閿熸枻鎷烽敓锟�	
	public double getAmountOfPaidUp() {
		double sum = 0;

		for (int i = 0; i < tenderList.size(); i++) {
//			if (tenderList.get(i).afterRoundingValue <=  tenderList.get(i).getPt_tender() && tenderList.get(i).afterRoundingValue > 0) {
//				sum += tenderList.get(i).afterRoundingValue;
//			}else{
				sum += tenderList.get(i).getPt_tender();
//			}
			
		}

		return BigDecmialTool.round(sum, 2);
	}
	
//	public double getOriginalAmountOfPaidUp() {
//		double sum = 0;
//
//		for (int i = 0; i < tenderList.size(); i++) {
//				sum += tenderList.get(i).getPt_tender();
//		}
//
//		return BigDecmialTool.round(sum, 2);
//	}
	

	// 閿熺獤闈╂嫹foodstamp
	public double getFoodstampOfPaidUp() {
		double sum = 0;

		if (tenderList != null) {
			for (int i = 0; i < tenderList.size(); i++) {
				if (tenderList.get(i).paymentType.equals(PaymentType.FOOD_STAMP)) {
					sum += tenderList.get(i).getPt_tender();
				}
			}
		}
		return BigDecmialTool.round(sum, 2);
	}

	public double getFoodstampTaxExemptByNj() {
		double totalfsexmpt = 0;
		totalfsexmpt = this.getTaxExempat();
		return BigDecmialTool.round(totalfsexmpt, 2);
	}
	
	public double getFoodstampTaxExemptByIllinois() {
		double totalfsexmpt = 0;
		totalfsexmpt = this.getTaxExempatByIllinois();
		return BigDecmialTool.round(totalfsexmpt, 2);
	}
	
	// 搴旈敓鏂ゆ嫹閿熸枻鎷烽敓锟�	
	public double getAmountPayable() {
		return getSubTotal() + getTransDiscount() + getTotalTax() + Rounding;
	}
	
	public boolean canPayFoodstamp(){
		boolean check = true;
		if (tenderList.size() >= 2) {
			return false;
		}
		if (tenderList != null ) {
			for (int i = 0; i < tenderList.size(); i++) {
				if (!tenderList.get(i).paymentType.equals(PaymentType.FOOD_STAMP)) {
					check = false;
				}
			}
		}
		return check;
	}

	public CouponSetting getCouponSetting() {
		return mCouponSetting;
	}

	public void setCouponSetting(CouponSetting mCouponSetting) {
		this.mCouponSetting = mCouponSetting;
	}

	public double getSubTotal() {
		double subTotal = 0;
		for (int i = 0; i < mSaleListItems.getItemCount(); i++) {
			subTotal += mSaleListItems.getItem(i).getPrice();
		}
		return BigDecmialTool.round(subTotal, 2);
	}

	public double getTotalTax() {
		double totalTax = 0;
//		if (this.mTaxExempat)
//			return 0;
		totalTax = this.getTax();
		if (getFoodstampOfPaidUp() > 0) {
			
			if (GlobalInfo.getInstance().foodStampRule == MoleQConstants.ILLINOIS) {
				totalTax = BigDecmialTool.round(totalTax, 2) + BigDecmialTool.round(getFoodstampTaxExemptByIllinois(), 2) * -1;
			}else{
				 totalTax = BigDecmialTool.round(totalTax, 2) + BigDecmialTool.round(getFoodstampTaxExemptByNj(), 2) * -1;
			}
			
		}
//		if (totalTax < 0)
//			totalTax = 0;
		return totalTax;
	}
	public double getCurrentTax() {
		double totalTax = 0;
		totalTax = this.getTax();
//		if (totalTax < 0)
//			totalTax = 0;
		return totalTax;
	}

	public double getTotalTaxExem() {
		double totalTax = 0;
		double taxRate1 = 0,taxRate2 = 2,taxRate3 = 3,taxRate4 = 4,taxRate5 = 5,taxRate6 = 6;
		
		for (int i = 0; i < getTaxSetting().size(); i++) {
			double taxRate = getTaxSetting().get(i).getTx_rate();
			switch (i) {
			case 0:
				taxRate1 = taxRate;
				break;
			case 1:
				taxRate2 = taxRate;
				break;
			case 2:
				taxRate3 = taxRate;
				break;
			case 3:
				taxRate4 = taxRate;
				break;
			case 4:
				taxRate5 = taxRate;
				break;
			case 5:
				taxRate6 = taxRate;
				break;
			}
		}
		
		totalTax = exemptTax1able * taxRate1 + exemptTax2able * taxRate2 + exemptTax3able * taxRate3 + exemptTax4able * taxRate4
					+exemptTax5able * taxRate5 + exemptTax6able * taxRate6;
		
		if (getFoodstampOfPaidUp() > 0) {
			if (GlobalInfo.getInstance().foodStampRule == MoleQConstants.ILLINOIS) {
				totalTax = totalTax + BigDecmialTool.round(getFoodstampTaxExemptByIllinois(), 2) * -1;
			}else{
				totalTax = totalTax + BigDecmialTool.round(getFoodstampTaxExemptByNj(), 2) * -1;
			}
		}
		
//		if (totalTax < 0)
//			totalTax = 0;
		return totalTax;
	}

	public double getExemptTax() {
		double totalTax = 0;
		if (getFoodstampOfPaidUp() > 0) {
			if (GlobalInfo.getInstance().foodStampRule == MoleQConstants.ILLINOIS) {
				totalTax = totalTax + BigDecmialTool.round(getFoodstampTaxExemptByIllinois(), 2) * -1;
			}else{
				totalTax = totalTax + BigDecmialTool.round(getFoodstampTaxExemptByNj(), 2) * -1;
			}
		}
		return BigDecmialTool.round(totalTax, 2) * -1;
	}
	
//	public double getTaxExempt(int TaxExempatnum) {
//		double exemptable = 0,totalExempTax =0;
//		int num = -1;
//		if (TaxExempatnum == 0) {
//			totalExempTax = getCurrentTax();
//		}else {
//		
//			for (int i = 0; i < mSaleListItems.getItemCount(); i++) {
//				
//				if (mSaleListItems.getItem(i).exemptTaxnum == 0) {
////					exemptable += mSaleListItems.getItem(i).getPrice();
////					totalExempTax =  calcTax(exemptable, getTaxSettingByNo(1));
//				}else{
//					boolean isExempt = mSaleListItems.getItem(i).getIsExemptTax(TaxExempatnum);
//					if (isExempt) {
//						exemptable += mSaleListItems.getItem(i).getPrice();
//					}
//					
//					if (TaxExempatnum == 1) totalExempTax = calcTax(exemptable, getTaxSettingByNo(1));
//					if (TaxExempatnum == 2) totalExempTax = calcTax(exemptable, getTaxSettingByNo(2));
//					if (TaxExempatnum == 3) totalExempTax = calcTax(exemptable, getTaxSettingByNo(3));
//					if (TaxExempatnum == 4) totalExempTax = calcTax(exemptable, getTaxSettingByNo(4));
//					if (TaxExempatnum == 5) totalExempTax = calcTax(exemptable, getTaxSettingByNo(5));
//					if (TaxExempatnum == 6) totalExempTax = calcTax(exemptable, getTaxSettingByNo(6));
//				}
//				}
//				
//			}
//			
//		
//		return BigDecmialTool.round(totalExempTax, 2) * -1;
//	}

	public double getItemDiscount() {
		double itemDiscount = 0;
		if (mSaleListItems.getItemCount() > 0) {
			for (int i = 0; i < mSaleListItems.getItemCount(); i++) {
				if (mSaleListItems.getItem(i).getItemType() == ItemType.ITEM_DISCOUNT_AMOUNT || mSaleListItems.getItem(i).getItemType() == ItemType.ITEM_DISCOUNT_PERECENT
						|| mSaleListItems.getItem(i).getItemType() == ItemType.ITEM_DISCOUNT_MANUAL) {
					itemDiscount += mSaleListItems.getItem(i).getPrice();
				}
			}
		}
		return itemDiscount * -1;
	}
	
	public double getItemCoupon() {
		double itemDiscount = 0;
		if (mSaleListItems.getItemCount() > 0) {
			for (int i = 0; i < mSaleListItems.getItemCount(); i++) {
				if (mSaleListItems.getItem(i).getItemType() == ItemType.ITEM_COUPON
						|| mSaleListItems.getItem(i).getItemType() == ItemType.COUPON) {
					itemDiscount += mSaleListItems.getItem(i).getPrice();
				}
			}
		}
		return itemDiscount * (-1);
	}
	
	public double getVdrCoupon() {
		double vdrDiscount = 0;
		if (mSaleListItems.getItemCount() > 0) {
			for (int i = 0; i < mSaleListItems.getItemCount(); i++) {
				if (mSaleListItems.getItem(i).getItemType() == ItemType.VDR_COUPON) {
					String[] temp = mSaleListItems.getItem(i).getVdrCouponBarcode();
					if(temp[0].equals("Vdr Coupon"))
						vdrDiscount += mSaleListItems.getItem(i).getPrice();
				}
			}
		}
		return vdrDiscount * (-1);
	}
	
	public double getMutlAddValueCoupon() {
		double vdrDiscount = 0;
		if (mSaleListItems.getItemCount() > 0) {
			for (int i = 0; i < mSaleListItems.getItemCount(); i++) {
				
				if (mSaleListItems.getItem(i).getItemType() == ItemType.VDR_COUPON) {
					String[] temp = mSaleListItems.getItem(i).getVdrCouponBarcode();
					if(temp[0].equals("Mult Vdr Coupon") || temp[0].equals("Add Value"))
						vdrDiscount += mSaleListItems.getItem(i).getPrice();
				}
			}
		}
		return vdrDiscount * (-1);
	}

	public double getTransDiscount() {
		double totalDiscount = 0;

		if(TransDntType.equals("")) return 0;
		
		for (int i = 0; i < mSaleListItems.getItemCount(); i++) {
			if (!mSaleListItems.getItem(i).getNodiscount()) {
				totalDiscount += mSaleListItems.getItem(i).getPrice() * TransDntValue * 0.01;
			}

		}
		
		return BigDecmialTool.round(totalDiscount, 2) * -1;
	}

	public double getFoodstamp() {

		double foodstamp = 0;
		for (int i = 0; i < mSaleListItems.getItemCount(); i++) {
			if (mSaleListItems.getItem(i).getFoodstamp()) {
				foodstamp += mSaleListItems.getItem(i).getPrice();
			}
		}

		if (foodstamp > getAmountPayable()) {

			foodstamp = getAmountPayable();
		}
		return BigDecmialTool.round(foodstamp, 2);
	}

	public double getChange() {

		return Math.abs(getAmountPayable() - getAmountOfPaidUp());
	}

//	public int getManualTaxExempat() {
//		return mTaxExempat;
//	}

	public void clearAllTender() {
		if (tenderList == null) {
			tenderList = new ArrayList<PosTender>();
		} else {
			tenderList.clear();
		}

	}

	public boolean isNeedSignature() {

		for (int i = 0; i < tenderList.size(); i++) {
			if (tenderList.get(i).paymentType == PaymentType.CREDIT_CARD) {
				return true;
			}
		}
		return false;
	}

	public ArrayList<PosTender> getTendersByPaymentType(PaymentType type) {
		ArrayList<PosTender> result = new ArrayList<PosTender>();
		for (int i = 0; i < tenderList.size(); i++) {
			if (tenderList.get(i).paymentType == type) {
				result.add(tenderList.get(i));
			}
		}
		return result;
	}

	public String toReceipt() {
		String result = "";
		PosPrinter printer = (PosPrinter) DeviceManager.getInstance().printer;
		int iTotalLen = 46;
		int iP4Len = 14;
		int iContentLen = iTotalLen - iP4Len;
		String sLine = "";
		String sPrice = "";
		int iLen = 0;
		boolean showTax = false;
		boolean showFootstamp = false;

		result += this.getHeaderContent();

		// this.appendBuffer("MoleQ Inc.     ",PosPrinter.FONT_DOUBLE_SIZE,PosPrinter.RIGHT);
		result += printer.toPrintContent("===============================================");
		if (isReprint) {
			result += printer.toPrintContent("*** REPRINT ***");
		}
		result += printer.toPrintContent("Station " + String.format("%02d", GlobalInfo.getInstance().stationNo) + "  " + String.format("%06d", TransactionNo));
		result += printer.toPrintContent(MoleQUtil.getDateToString("yyyy-MM-dd", dDoneDate) + " " + MoleQUtil.getDateToString("HH:mm:ss", dDoneDate));
		result += printer.toPrintContent("Cashier # " + GlobalInfo.getInstance().cashier);
		result += printer.toPrintContent("");
		if (TransType == TransactionType.RETURN) {
			result += printer.toPrintContent("---------", PosPrinter.FONT_SINGLE_SIZE, PosPrinter.CENTER);
			result += printer.toPrintContent("Refund", PosPrinter.FONT_SINGLE_SIZE, PosPrinter.CENTER);
			result += printer.toPrintContent("---------", PosPrinter.FONT_SINGLE_SIZE, PosPrinter.CENTER);
			result += printer.toPrintContent("");
		}

		result += getSaleDetailContent();
		result += printer.toPrintContent("-----------------------------------------------");
		sLine = "";
		sLine = "Item Count:";
		sLine = StringUtils.getString(" ", iTotalLen / 2 - sLine.length()) + sLine;
		sPrice = "  " + mSaleListItems.getItemCountForReceipt() + "  ";
		iLen = iP4Len - sPrice.length();
		if (iLen == 0) {
			sLine += sPrice;
		} else {
			sLine += StringUtils.getString(" ", iLen) + sPrice;

		}
		result += printer.toPrintContent(sLine);

		sLine = "";
		sLine = "Subtotal:";
		sLine = StringUtils.getString(" ", iTotalLen / 2 - sLine.length()) + sLine;
		//sPrice = "  " + MoleQUtil.fixPrintPrice(getSubTotal() + getTransDiscount() + getCoupon()) + " ";
		sPrice = "  " + MoleQUtil.fixPrintPrice(getSubTotal() + getTransDiscount() ) + " ";
		iLen = iP4Len - sPrice.length();
		if (iLen == 0) {
			sLine += sPrice;
		} else {
			sLine += StringUtils.getString(" ", iLen) + sPrice;

		}
		result += printer.toPrintContent(sLine);

		if (getTransDiscount() != 0) {
			sLine = "";
			sLine = TransDntValue + "% Discount:";
			sLine = StringUtils.getString(" ", iTotalLen / 2 - sLine.length()) + sLine;
			sPrice = "  " + MoleQUtil.fixPrintPrice(getTransDiscount()) + " ";
			iLen = iP4Len - sPrice.length();
			if (iLen == 0) {
				sLine += sPrice;
			} else {
				sLine += StringUtils.getString(" ", iLen) + sPrice;

			}
			result += printer.toPrintContent(sLine);
		}

		sLine = "";
		sLine = "Tax:";
		sLine = StringUtils.getString(" ", iTotalLen / 2 - sLine.length()) + sLine;
		sPrice = "  " + MoleQUtil.fixPrintPrice(getCurrentTax()) + " ";
		iLen = iP4Len - sPrice.length();
		if (iLen == 0) {
			sLine += sPrice;
		} else {
			sLine += StringUtils.getString(" ", iLen) + sPrice;

		}
		result += printer.toPrintContent(sLine);

		double TaxExempat = 0;
		// get manual taxExempt
//		if (mTaxExempat >= 0) {
//			TaxExempat = getCurrentTax() * -1;
//		} else if (getFoodstampOfPaidUp() > 0) {
//			TaxExempat = getExemptTax();
//		}
		TaxExempat = getTotalTaxExem() * -1;

		if (BigDecmialTool.round(TaxExempat, 2) < 0) {
			sLine = "";
			sLine = "Tax Exempt:";
			sLine = StringUtils.getString(" ", iTotalLen / 2 - sLine.length()) + sLine;
			sPrice = "  " + MoleQUtil.fixPrintPrice(TaxExempat) + " ";
			iLen = iP4Len - sPrice.length();
			if (iLen == 0) {
				sLine += sPrice;
			} else {
				sLine += StringUtils.getString(" ", iLen) + sPrice;

			}
			result += printer.toPrintContent(sLine);
		}

		//rounding
		if (Rounding_flag.equals("1")) {
			sLine = "";
			sLine = "Rouding:";
			sLine = StringUtils.getString(" ", iTotalLen / 2 - sLine.length()) + sLine;
			sPrice = "  " + MoleQUtil.fixPrintPrice(Rounding) + " ";
			iLen = iP4Len - sPrice.length();
			if (iLen == 0) {
				sLine += sPrice;
			} else {
				sLine += StringUtils.getString(" ", iLen) + sPrice;
				
			}
			result += printer.toPrintContent(sLine);
		}
		
		sLine = "";
		sLine = "Total:";
		sLine = StringUtils.getString(" ", iTotalLen / 2 - sLine.length()) + sLine;
		sPrice = "  " + MoleQUtil.fixPrintPrice(getAmountPayable()) + " ";
		iLen = iP4Len - sPrice.length();
		if (iLen == 0) {
			sLine += sPrice;
		} else {
			sLine += StringUtils.getString(" ", iLen) + sPrice;

		}
		result += printer.toPrintContent(sLine);

		sLine = "";
		sLine = "Tender:";
		sLine = StringUtils.getString(" ", iTotalLen / 2 - sLine.length()) + sLine;
		sPrice = "  " + MoleQUtil.fixPrintPrice(getAmountOfPaidUp()) + " ";
		iLen = iP4Len - sPrice.length();
		if (iLen == 0) {
			sLine += sPrice;
		} else {
			sLine += StringUtils.getString(" ", iLen) + sPrice;

		}
		result += printer.toPrintContent(sLine);

		sLine = "";
		sLine = "Change:";
		sLine = StringUtils.getString(" ", iTotalLen / 2 - sLine.length()) + sLine;
		sPrice = "  " + MoleQUtil.fixPrintPrice(getChange()) + " ";
		iLen = iP4Len - sPrice.length();
		if (iLen == 0) {
			sLine += sPrice;
		} else {
			sLine += StringUtils.getString(" ", iLen) + sPrice;

		}
		result += printer.toPrintContent(sLine);

		if (tenderList.size() > 0) {
			result += printer.toPrintContent("--------------  Tender Detail  ---------------");
			for (int i = 0; i < tenderList.size(); i++) {
				sLine = "";
				sLine = tenderList.get(i).paymentType.getText().toString() + ":";
				sLine = StringUtils.getString(" ", iTotalLen / 2 - sLine.length()) + sLine;
				sPrice = "  " + MoleQUtil.fixPrintPrice(tenderList.get(i).getPt_tender()) + " ";
				iLen = iP4Len - sPrice.length();
				if (iLen == 0) {
					sLine += sPrice;
				} else {
					sLine += StringUtils.getString(" ", iLen) + sPrice;

				}
				result += printer.toPrintContent(sLine);
				
				if (!tenderList.get(i).getPt_card_no().equals("")) {
					sLine = "";
					sLine = tenderList.get(i).getPt_card_no() + "   " + tenderList.get(i).getPt_card_type();
					sLine = "            " + sLine;
					result += printer.toPrintContent(sLine);
				}

				String sAuth = tenderList.get(i).getPt_Auth();
				if (sAuth != null && !sAuth.equals("")) {
					sLine = "";
					if (tenderList.get(i).paymentType == PaymentType.CHECK) {
						sLine = "Check #:";
					} else {
						sLine = "Auth #:";
					}

					sLine = StringUtils.getString(" ", iTotalLen / 2 - sLine.length()) + sLine;
					sPrice = "  " + sAuth + " ";
					iLen = iP4Len - sPrice.length();
					if (iLen == 0) {
						sLine += sPrice;
					} else {
						sLine += StringUtils.getString(" ", iLen) + sPrice;

					}
					result += printer.toPrintContent(sLine);
				}

			}

		}

		result += printer.toPrintContent("===============================================");
		// this.appendBuffer("Thank you for shopping.");
		List<Receipt> footerlst = ServiceManager.getInstance().mReceiptService.FindALLTrailer();
		if (footerlst != null) {
			for (int k = 0; k < footerlst.size(); k++) {
				int align = 0, fontSize = 10;

				if (footerlst.get(k).getLarge().equals("L")) {
					fontSize = PosPrinter.FONT_DOUBLE_SIZE;
				} else if (footerlst.get(k).getLarge().equals("N")) {
					fontSize = PosPrinter.FONT_SINGLE_SIZE;
				}

				if (footerlst.get(k).getJustify().equals("L")) {
					align = PosPrinter.LEFT;
				} else if (footerlst.get(k).getJustify().equals("C")) {
					align = PosPrinter.CENTER;
				} else if (footerlst.get(k).getJustify().equals("R")) {
					align = PosPrinter.RIGHT;
				}
				result += printer.toPrintContent(footerlst.get(k).getMsg(), fontSize, align);

			}
		}

		return result;
	}
	
	public String toServiceTicketLocalReceipt(List<SaleListItem> listItem) {
		String result = "";
		PosPrinter printer = (PosPrinter) DeviceManager.getInstance().printer;
		if (haveServiceItem()) {
			result += "\n\n" + this.getHeaderContent();
			result += printer.toPrintContent("===============================================");
			if (isReprint) {
				result += printer.toPrintContent("*** REPRINT ***");
			}
//			result += printer.toPrintContent("Service  Ticket   " + String.format("%02d", GlobalInfo.getInstance().stationNo) + TransactionNo);
			result += printer.toPrintContent("Station " + String.format("%02d", GlobalInfo.getInstance().stationNo) + "  " + String.format("%06d", TransactionNo));
			result += printer.toPrintContent(MoleQUtil.getDateToString("yyyy-MM-dd", dDoneDate) + " " + MoleQUtil.getDateToString("HH:mm:ss", dDoneDate));
			result += printer.toPrintContent("");
			
			result += printer.toPrintContent("             --------------------              ");
			result += printer.toPrintContent("                SERVICE TICKET                 ");
			result += printer.toPrintContent("             --------------------              ");
			result += printer.toPrintContent("");
			result += printer.toPrintContent("                SERVICE # " + String.format("%02d", GlobalInfo.getInstance().stationNo) + TransactionNo);
			result += printer.toPrintContent("");
			
			result += getServiceDetailContent(listItem);
			
			result += printer.toPrintContent("-----------------------------------------------");
			result += printer.toPrintContent("PLEASE USE THIS TICKET TO PICKUP YOUR          ");
			result += printer.toPrintContent("ITEMS IN THE SERVICE DEPARTMENT                ");
			result += printer.toPrintContent("===============================================");
			result += this.getFooterContent();
		}
		return result;
	}
	
	public String toServiceTicketReceipt(List<SaleListItem> listItem) {
		String result = "";
		PosPrinter printer = (PosPrinter) DeviceManager.getInstance().printer;
		if (haveServiceItem()) {
			result += "\n\n";
			
			result += printer.toPrintContent("Service  Ticket   " + String.format("%02d", GlobalInfo.getInstance().stationNo) + TransactionNo);
			result += printer.toPrintContent("Station " + String.format("%02d", GlobalInfo.getInstance().stationNo) + "  " + String.format("%06d", TransactionNo));
			result += printer.toPrintContent(MoleQUtil.getDateToString("yyyy-MM-dd", dDoneDate) + " " + MoleQUtil.getDateToString("HH:mm:ss", dDoneDate));
			result += printer.toPrintContent("");
			
//			result += printer.toPrintContent("             --------------------              ");
//			result += printer.toPrintContent("                SERVICE TICKET                 ");
//			result += printer.toPrintContent("             --------------------              ");
//			result += printer.toPrintContent("");
//			result += printer.toPrintContent("                SERVICE # " + String.format("%02d", GlobalInfo.getInstance().stationNo) + TransactionNo);
//			result += printer.toPrintContent("");
			result += printer.toPrintContent("===============================================");
			result += getServiceDetailContent(listItem);
			result += printer.toPrintContent("");
			result += printer.toPrintContent("===============================================");
		}
		return result;
	}
	
	public String getServiceDetailContent(List<SaleListItem> listItem) {
		String result = "";
		int iTotalLen = 46;
		int iP4Len = 14;
		int iQtyLen = 6;
		int iContentLen = iTotalLen - iP4Len - iQtyLen;
		String sLine = "";
		int iLen = 0;
		PosPrinter printer = (PosPrinter) DeviceManager.getInstance().printer;
		for (int i = 0; i < listItem.size(); i++) {
			sLine = "";

			SaleListItem saleitem = listItem.get(i);
			iLen = 0;
			String sQty = String.valueOf(saleitem.getQty());
			iLen = sQty.length();
			sLine += sQty + StringUtils.getString(" ", iQtyLen- iLen);
			String sName = saleitem.getName();
			iLen = sLine.length();
			
			if (sName.length() + iLen > iContentLen) {
				
				sName = sName.substring(0, iContentLen - iLen);
				sLine += sName;
			} else {
				iLen = iContentLen - (sName.length() + iLen);
				sLine += sName + StringUtils.getString(" ", iLen);
			}
			result += printer.toPrintContent(sLine);
		}

		return result;
	}

	public String getCreditContent(PosTender tender) {
		PosPrinter printer = (PosPrinter) DeviceManager.getInstance().printer;
		String result = "";
		if (tender.paymentType == PaymentType.CREDIT_CARD) {
			result += printer.toPrintContent("                                               ");
			result += getHeaderContent();
			result += printer.toPrintContent("===============================================");
			if (isReprint) {
				result += printer.toPrintContent("*** REPRINT ***");
			}
			result += printer.toPrintContent("Station " + String.format("%02d", GlobalInfo.getInstance().stationNo) + "  " + String.format("%06d", TransactionNo));
			result += printer.toPrintContent(MoleQUtil.getDateToString("yyyy-MM-dd", dDoneDate) + " " + MoleQUtil.getDateToString("HH:mm:ss", dDoneDate));
			result += printer.toPrintContent("Cashier # " + GlobalInfo.getInstance().cashier);
			result += printer.toPrintContent("                                               ");
			result += printer.toPrintContent("CREDIT CARD PAYMENT       " + MoleQUtil.fixPrintPrice(tender.getPt_tender()));
			if (!tender.getPt_card_no().equals("")) {
				result += printer.toPrintContent(tender.getPt_card_no() + "   " + tender.getPt_card_type());
			}
			result += printer.toPrintContent("AUTH     " + tender.getPt_Auth());
			result += printer.toPrintContent("                                               ");
			result += printer.toPrintContent("CARD HOLDER ACKNOWLENDGES RECEIPT OF");
			result += printer.toPrintContent("GOODS/SERVICES EQUAL TO THE AMOUNT SET");
			result += printer.toPrintContent("FORTH ABOVE AND AGREES TO ABIDE BY THE");
			result += printer.toPrintContent("ISSUERS AGREEMENT WITH THE CARDHOLDER");
			result += printer.toPrintContent("                                               ");
			result += printer.toPrintContent("                                               ");
			result += printer.toPrintContent("                                               ");
			result += printer.toPrintContent("                                               ");
			result += printer.toPrintContent("X _____________________________________________");
			result += printer.toPrintContent("                  SIGNATURE                    ");
			result += printer.toPrintContent("                                               ");
			result += printer.toPrintContent("===============================================");
			result += getFooterContent();
			result += printer.toPrintContent("                                               ");

		}
		return result;
	}
	
	public String getViewCreditContent(PosTender tender, PosTrns mPosTrns) {
		PosPrinter printer = (PosPrinter) DeviceManager.getInstance().printer;
		String result = "";
		if (tender.paymentType == PaymentType.CREDIT_CARD) {
			result += printer.toPrintContent("                                               ");
			result += getHeaderContent();
			result += printer.toPrintContent("===============================================");
			if (isReprint) {
				result += printer.toPrintContent("*** REPRINT ***");
			}
			result += printer.toPrintContent("Station " + String.format("%02d", mPosTrns.getPt_station()) + "  " + String.format("%06d", mPosTrns.getPt_no()));
			result += printer.toPrintContent(MoleQUtil.getDateToString("yyyy-MM-dd", dDoneDate) + " " + MoleQUtil.getDateToString("HH:mm:ss", dDoneDate));
			result += printer.toPrintContent("Cashier # " + mPosTrns.getPt_user_id());
			result += printer.toPrintContent("                                               ");
			result += printer.toPrintContent("CREDIT CARD PAYMENT       " + MoleQUtil.fixPrintPrice(tender.getPt_tender()));
			if (!tender.getPt_card_no().equals("")) {
				result += printer.toPrintContent(tender.getPt_card_no() + "   " + tender.getPt_card_type());
			}
			result += printer.toPrintContent("AUTH     " + tender.getPt_Auth());
			result += printer.toPrintContent("                                               ");
			result += printer.toPrintContent("CARD HOLDER ACKNOWLENDGES RECEIPT OF");
			result += printer.toPrintContent("GOODS/SERVICES EQUAL TO THE AMOUNT SET");
			result += printer.toPrintContent("FORTH ABOVE AND AGREES TO ABIDE BY THE");
			result += printer.toPrintContent("ISSUERS AGREEMENT WITH THE CARDHOLDER");
			
		}
		return result;
	}
	
	public String getViewCreditFoot() {
		PosPrinter printer = (PosPrinter) DeviceManager.getInstance().printer;
		String result = "";

		result += printer.toPrintContent("X _____________________________________________");
		result += printer.toPrintContent("                  SIGNATURE                    ");
		result += printer.toPrintContent("                                               ");
		result += printer.toPrintContent("===============================================");
		result += getFooterContent();
		result += printer.toPrintContent("                                               ");
		return result;
	}

	public String getHeaderContent() {
		PosPrinter printer = (PosPrinter) DeviceManager.getInstance().printer;
		String result = "";
		List<Receipt> hearderlst = ServiceManager.getInstance().mReceiptService.FindALLHeader();
		if (hearderlst != null) {
			for (int k = 0; k < hearderlst.size(); k++) {
				int align = 0, fontSize = 10;

				if (hearderlst.get(k).getLarge().equals("L")) {
					fontSize = PosPrinter.FONT_DOUBLE_SIZE;
				} else if (hearderlst.get(k).getLarge().equals("N")) {
					fontSize = PosPrinter.FONT_SINGLE_SIZE;
				}

				if (hearderlst.get(k).getJustify().equals("L")) {
					align = PosPrinter.LEFT;
				} else if (hearderlst.get(k).getJustify().equals("C")) {
					align = PosPrinter.CENTER;
				} else if (hearderlst.get(k).getJustify().equals("R")) {
					align = PosPrinter.RIGHT;
				}
				result += printer.toPrintContent(hearderlst.get(k).getMsg(), fontSize, align);

			}
		}
		//Demo 
//		result = printer.toPrintContent("MOLEQ POS SYSTEM DEMO ONLY", PosPrinter.FONT_SINGLE_SIZE, PosPrinter.LEFT);
		return result;
	}

	public String getFooterContent() {
		PosPrinter printer = (PosPrinter) DeviceManager.getInstance().printer;
		String result = "";
		List<Receipt> footerlst = ServiceManager.getInstance().mReceiptService.FindALLTrailer();
		if (footerlst != null) {
			for (int k = 0; k < footerlst.size(); k++) {
				int align = 0, fontSize = 10;

				if (footerlst.get(k).getLarge().equals("L")) {
					fontSize = PosPrinter.FONT_DOUBLE_SIZE;
				} else if (footerlst.get(k).getLarge().equals("N")) {
					fontSize = PosPrinter.FONT_SINGLE_SIZE;
				}

				if (footerlst.get(k).getJustify().equals("L")) {
					align = PosPrinter.LEFT;
				} else if (footerlst.get(k).getJustify().equals("C")) {
					align = PosPrinter.CENTER;
				} else if (footerlst.get(k).getJustify().equals("R")) {
					align = PosPrinter.RIGHT;
				}
				result += printer.toPrintContent(footerlst.get(k).getMsg(), fontSize, align);

			}
		}
		return result;
	}

	public String getNoSaleContent() {
		String result = "";

		PosPrinter printer = (PosPrinter) DeviceManager.getInstance().printer;
		result += getHeaderContent();
		result += printer.toPrintContent("===============================================");
		result += getPosInfoContent();
		result += printer.toPrintContent("       *********************************       ");
		result += printer.toPrintContent("       *****  No Sale Transaction  *****       ");
		result += printer.toPrintContent("       *********************************       ");
		result += printer.toPrintContent("===============================================");
		result += this.getFooterContent();
		return result;
	}

	public String getPosInfoContent() {
		String result = "";

		PosPrinter printer = (PosPrinter) DeviceManager.getInstance().printer;

		result += printer.toPrintContent("Station " + String.format("%02d", GlobalInfo.getInstance().stationNo) + "  " + String.format("%06d", TransactionNo));
		result += printer.toPrintContent(MoleQUtil.getDateToString("yyyy-MM-dd", dDoneDate) + " " + MoleQUtil.getDateToString("HH:mm:ss", dDoneDate));
		result += printer.toPrintContent("Cashier # " + GlobalInfo.getInstance().cashier);
		result += printer.toPrintContent("                                               ");

		return result;
	}

	public void SaveEJ(String context) {
		Date now = new Date();
		PosEJ obj = new PosEJ();
		obj.setEj_no(TransactionNo);
		obj.setEj_content(context);
		obj.setEj_date(trnDate);
		obj.setEj_crt_date(MoleQUtil.getDateToString("yyyyMMdd", now));
		obj.setEj_crt_time(MoleQUtil.getDateToString("HHmmss", now));
		ServiceManager.getInstance().mPosEJService.Insert(obj);
	}
	
	public String getDescription(String description,String sPrice){
		
		int iTotalLen = 46;
		int iP4Len = 14;
		int iContentLen = iTotalLen - iP4Len;
		
		int iLen = 0;
		if (description.length() + iLen > iContentLen) {

			description = description.substring(0, iContentLen - iLen);
		} else {
			iLen = iContentLen - (description.length() + iLen);
			description = description + StringUtils.getString(" ", iLen);
		}
		
		iLen = iP4Len - sPrice.length();
		if (iLen == 0) {
			description += sPrice;
		} else {
			description += StringUtils.getString(" ", iLen) + sPrice;

		}
		
		return description;
	}

	public String getSaleDetailContent() {
		String result = "";
		String description = "";
		int iTotalLen = 46;
		int iP4Len = 14;
		int iContentLen = iTotalLen - iP4Len;
		String sLine = "";
		String sPrice = "";
		int iLen = 0;
		boolean showTax = false;
		boolean showFootstamp = false;
		PosPrinter printer = (PosPrinter) DeviceManager.getInstance().printer;
		for (int i = 0; i < mSaleListItems.getItemCount(); i++) {
			sLine = "";

			SaleListItem saleitem = mSaleListItems.getItem(i);
//			String sName = mSaleListItems.getItem(i).getName();
			//get refund name
//			String sName = mSaleListItems.getItem(i).getDisplayContent();
			String sName = saleitem.getName();
			if (saleitem.getItemType() == ItemType.PACKAGE_PRICE_FIX || saleitem.getItemType() == ItemType.LIMITED_QTY_PRICE_FIX
				||	saleitem.getItemType() == ItemType.DISCOUNT_AMOUNT || saleitem.getItemType() == ItemType.DISCOUNT_PERECENT
				||	saleitem.getItemType() == ItemType.DISCOUNT_LINK) {
				sName = mSaleListItems.getItem(i).getDisplayContent();
			}
			if (saleitem.isRefund()) {
				if (saleitem.getItemType() == ItemType.REGULAR || saleitem.getItemType() == ItemType.OPEN_DEPARTMENT || saleitem.getItemType() == ItemType.PACKAGE_PRICE
						) {
					sName = sName + " (Refund)";
				}
			}
			// qty
//			if ((saleitem.getItemType() == ItemType.REGULAR || saleitem.getItemType() == ItemType.OPEN_DEPARTMENT) 
//					&& !saleitem.getEachDescription().equals("")) {
//				String sQty = String.valueOf(saleitem.getQty());
//				sName = sQty + " " + sName;
//			}
			
			iLen = sLine.length();
			if (sName.length() + iLen > iContentLen) {

				sName = sName.substring(0, iContentLen - iLen);
				sLine += sName;
			} else {
				iLen = iContentLen - (sName.length() + iLen);
				sLine += sName + StringUtils.getString(" ", iLen);
			}

			showTax = false;
			showFootstamp = false;
			if (saleitem.getTax1() || saleitem.getTax2() || saleitem.getTax3() || saleitem.getTax4() || saleitem.getTax5() || saleitem.getTax6()) {
				showTax = true;
			}

			if (saleitem.getFoodstamp()) {
				showFootstamp = true;
			}

			sPrice = "  " + MoleQUtil.fixPrintPrice(saleitem.getPrice(), showFootstamp, showTax);

			if (!mSaleListItems.getItem(i).getEachDescription().equals("")) {
				description = mSaleListItems.getItem(i).getEachDescription();
				
				description = getDescription(description,sPrice);
				
				result += printer.toPrintContent(description);
				
				
			}else if (!mSaleListItems.getItem(i).getPriceDescription().equals("")) {
				description = mSaleListItems.getItem(i).getPriceDescription() + mSaleListItems.getItem(i).getmTareDesc();
				
				description = getDescription(description,sPrice);
				
				result += printer.toPrintContent(description);
			}else if (!mSaleListItems.getItem(i).getDepDescription().equals("")) {
				description = mSaleListItems.getItem(i).getDepDescription() + mSaleListItems.getItem(i).getmTareDesc();
				
				description = getDescription(description,sPrice);
				
				result += printer.toPrintContent(description);
			}else{
				
				iLen = iP4Len - sPrice.length();
				if (iLen == 0) {
					sLine += sPrice;
				} else {
					sLine += StringUtils.getString(" ", iLen) + sPrice;

				}
			}
			
			// price

			result += printer.toPrintContent(sLine);
			if (GlobalInfo.getInstance().isShowDesc && !mSaleListItems.getItem(i).getDescription().equals("")) {
				result +=printer.toPrintContent(mSaleListItems.getItem(i).getDescription());
			}
			
		}

		return result;
	}

	// cancel transaction receipt
	public String getCancelContent() {
		String result = "";
		int iTotalLen = 46;
		int iP4Len = 12;
		int iContentLen = iTotalLen - iP4Len;
		String sLine = "";
		String sPrice = "";
		int iLen = 0;

		PosPrinter printer = (PosPrinter) DeviceManager.getInstance().printer;
		result += getHeaderContent();
		result += printer.toPrintContent("===============================================");
		result += getPosInfoContent();
		result += getSaleDetailContent();
		result += printer.toPrintContent("                                               ");
		result += printer.toPrintContent("-----------------------------------------------");

		// change
		sLine = "";
		sLine = "Item Count:";
		sLine = StringUtils.getString(" ", iTotalLen / 2 - sLine.length()) + sLine;
		sPrice = "  " + mSaleListItems.getItemCountForReceipt() + "  ";
		iLen = iP4Len - sPrice.length();
		if (iLen == 0) {
			sLine += sPrice;
		} else {
			sLine += StringUtils.getString(" ", iLen) + sPrice;

		}
		result += printer.toPrintContent(sLine);

		sLine = "";
		sLine = "Subtotal:";
		sLine = StringUtils.getString(" ", iTotalLen / 2 - sLine.length()) + sLine;
		sPrice = "  " + MoleQUtil.fixPrintPrice(getSubTotal() + getTransDiscount()) + " ";
		iLen = iP4Len - sPrice.length();
		if (iLen == 0) {
			sLine += sPrice;
		} else {
			sLine += StringUtils.getString(" ", iLen) + sPrice;

		}
		result += printer.toPrintContent(sLine);

		if (getTransDiscount() != 0) {
			sLine = "";
			sLine = TransDntValue + "% Discount:";
			sLine = StringUtils.getString(" ", iTotalLen / 2 - sLine.length()) + sLine;
			sPrice = "  " + MoleQUtil.fixPrintPrice(getTransDiscount()) + " ";
			iLen = iP4Len - sPrice.length();
			if (iLen == 0) {
				sLine += sPrice;
			} else {
				sLine += StringUtils.getString(" ", iLen) + sPrice;

			}
			result += printer.toPrintContent(sLine);
		}

		sLine = "";
		sLine = "Tax:";
		sLine = StringUtils.getString(" ", iTotalLen / 2 - sLine.length()) + sLine;
		sPrice = "  " + MoleQUtil.fixPrintPrice(getCurrentTax()) + " ";
		iLen = iP4Len - sPrice.length();
		if (iLen == 0) {
			sLine += sPrice;
		} else {
			sLine += StringUtils.getString(" ", iLen) + sPrice;

		}
		result += printer.toPrintContent(sLine);

		double TaxExempat = 0;
		// get manual taxexmpat
//		if (mTaxExempat >= 0) {
//			TaxExempat = getCurrentTax() * -1;
//		} else if (getFoodstampOfPaidUp() > 0) {
//			TaxExempat = getExemptTax();
//		}
		TaxExempat = getTotalTaxExem() * -1;

		if (BigDecmialTool.round(TaxExempat, 2) < 0) {
			sLine = "";
			sLine = "Tax Exempt:";
			sLine = StringUtils.getString(" ", iTotalLen / 2 - sLine.length()) + sLine;
			sPrice = "  " + MoleQUtil.fixPrintPrice(TaxExempat) + " ";
			iLen = iP4Len - sPrice.length();
			if (iLen == 0) {
				sLine += sPrice;
			} else {
				sLine += StringUtils.getString(" ", iLen) + sPrice;

			}
			result += printer.toPrintContent(sLine);
		}

		sLine = "";
		sLine = "Total:";
		sLine = StringUtils.getString(" ", iTotalLen / 2 - sLine.length()) + sLine;
		sPrice = "  " + MoleQUtil.fixPrintPrice(getAmountPayable()) + " ";
		iLen = iP4Len - sPrice.length();
		if (iLen == 0) {
			sLine += sPrice;
		} else {
			sLine += StringUtils.getString(" ", iLen) + sPrice;

		}
		result += printer.toPrintContent(sLine);
		result += printer.toPrintContent("       ***********************************     ");
		result += printer.toPrintContent("       ***            VOID             ***     ");
		result += printer.toPrintContent("       ***    Transaction Canceled     ***     ");
		result += printer.toPrintContent("       ***********************************     ");
		result += printer.toPrintContent("===============================================");
		result += getFooterContent();

		return result;
	}


	public void UpdatePosTrn() {

		dDoneDate = new Date();

		PosTrns posTrns = ServiceManager.getInstance().mPosTrnsService.GetTrn(TransactionNo);
		if(posTrns == null)  return;
		posTrns.setPt_date(trnDate);
		posTrns.setPt_done_date(MoleQUtil.getDateToString("yyyyMMdd", dDoneDate));
		posTrns.setPt_done_time(MoleQUtil.getDateToString("HHmmss", dDoneDate));
		posTrns.setPt_status(mTransType);
		double total = getSubTotal();
		double tax = getTotalTax();
		double tax_exem = 0;
		// get manual taxexempat
//		if (mTaxExempat >= 0) {
//			tax_exem = BigDecmialTool.round(getTotalTaxExem() * (-1), 2);
//		} else if (getFoodstampOfPaidUp() > 0) {
//			tax_exem = BigDecmialTool.round(getFoodstampTaxExempt(), 2);
//		}
		tax_exem = getTotalTaxExem();
		if (MoleQUtil.getTransType(TransType).equals("R")) {
			total = total * (-1);
			tax = tax * (-1);
			tax_exem = tax_exem * (-1);
			GlobalInfo.getInstance().useFuntionsList.add(GlobalInfo.getInstance().CurrentFreeFuncID);
			SaveFreeFuncRpt(FreeFuncRpt.FF_REFUND, 1, total);
		}
		if (mTransType.equals("X")) {
			total = total * (-1);
			tax = tax * (-1);
			tax_exem = tax_exem * (-1);
		}
		posTrns.setPt_total(BigDecmialTool.round(total, 2));
		posTrns.setPt_tax(BigDecmialTool.round(tax, 2));
		posTrns.setPt_tax_exem(BigDecmialTool.round(tax_exem, 2));
		posTrns.setPt_no(TransactionNo);
		posTrns.setPt_user_id(GlobalInfo.getInstance().cashier);
		posTrns.setPt_type(MoleQUtil.getTransType(TransType));
		if (managerID.equals("")) {
			posTrns.setPt_manager_id(null);
		}else {
			posTrns.setPt_manager_id(managerID);
		}
		ServiceManager.getInstance().mPosTrnsService.Update(posTrns);
	}

	public void SaveFreeFuncRpt(int ff_func_id, int ff_qty, double ff_amt) {

		if (ff_func_id == FreeFuncRpt.NONE)
			return;

		dDoneDate = new Date();
		FreeFuncRpt freeFuncRpt = new FreeFuncRpt();
		freeFuncRpt.setFf_store_id(GlobalInfo.getInstance().storeNo);
		freeFuncRpt.setFf_station(GlobalInfo.getInstance().stationNo);
		freeFuncRpt.setFf_date(trnDate);
		freeFuncRpt.setFf_func_id(ff_func_id);
		freeFuncRpt.setFf_qty(ff_qty);
		freeFuncRpt.setFf_amt(ff_amt);
		freeFuncRpt.setFf_user_id(GlobalInfo.getInstance().cashier);
		ServiceManager.getInstance().mFreeFuncRptService.InsertOrUpdate(freeFuncRpt);
		GlobalInfo.getInstance().CurrentFreeFuncID = FreeFuncRpt.NONE;
	}

	public void NoSaleTransaction() {
		dDoneDate = new Date();
		TransactionNo = this.generateID();
		String cashier = GlobalInfo.getInstance().cashier.toString();
		String date = MoleQUtil.getDateToString("yyyyMMdd", dDoneDate);
		String time = MoleQUtil.getDateToString("HHmmss", dDoneDate);
		int openTime = Integer.valueOf(GlobalInfo.getInstance().openTime);
		int closeTime = Integer.valueOf(GlobalInfo.getInstance().closeTime);
		if (closeTime < openTime) {
			if (Integer.valueOf(time) < closeTime) {
				trnDate = MoleQUtil.getNowPreDate();
			} else {
				trnDate = date;
			}
		} else {
			trnDate = date;
		}
		PosTrns posTrns = new PosTrns();
		posTrns.setPt_no(TransactionNo);
		posTrns.setPt_date(trnDate);
		posTrns.setPt_store_no(GlobalInfo.getInstance().storeNo);
		posTrns.setPt_station(GlobalInfo.getInstance().stationNo);
		posTrns.setPt_crt_date(date);
		posTrns.setPt_crt_time(time);
		posTrns.setPt_done_date(date);
		posTrns.setPt_done_time(time);
		posTrns.setPt_status("N");
		posTrns.setPt_user_id(cashier);
		posTrns.setPt_total(0);
		posTrns.setPt_tax(0);
		posTrns.setPt_tax_exem(0);
		posTrns.setPt_cmr_birthday("");
		posTrns.setPt_type("N");
		posTrns.setPt_manager_id(null);
		ServiceManager.getInstance().mPosTrnsService.Insert(posTrns);

	}

	public void CancelTransaction() {
		// clear pos line item
		ServiceManager.getInstance().mPosLineTaresService.DeleteByAll();
		ServiceManager.getInstance().mPosLineItemService.DeleteAll();
		ServiceManager.getInstance().mPosLineDiscntService.DeleteByAll();
		ServiceManager.getInstance().mPosLineCouponService.DeleteByAll();
		ServiceManager.getInstance().mPosLineCvvWicService.DeleteByAll();
		ServiceManager.getInstance().mPoslineTenderService.DeleteAll();
		mTransType = "X";
		UpdatePosTrn();

	}

	public void CompleteTransaction() {
		if (mSaleListItems != null && mSaleListItems.getItemCount() > 0) {
			ServiceManager.getInstance().mPosLineTaresService.DeleteByAll();
			ServiceManager.getInstance().mPosLineItemService.DeleteAll();
			ServiceManager.getInstance().mPosLineDiscntService.DeleteByAll();
			ServiceManager.getInstance().mPosLineCouponService.DeleteByAll();
			ServiceManager.getInstance().mPosLineCvvWicService.DeleteByAll();
			ServiceManager.getInstance().mPoslineTenderService.DeleteAll();
			mSaleListItems.SaveGroupSalesRpt();
			mSaleListItems.SaveDepSalesRpt();
//			mSaleListItems.SavePluSalesRpt();
			mSaleListItems.SavePluSalesRpt3();
			mSaleListItems.SaveMultiTareSalesRpt();
			mSaleListItems.SaveFixedTotalRpt();
		}
		status = TransactionStatus.CLOSED;
	}

	public String getRefNum() {
		int trnNo = TransactionNo;
		return String.format("##", GlobalInfo.getInstance().stationNo) + 
				String.format("#######", trnNo) + String.format("##", tenderList.size());
	}

	public void announceChanges() {
		mSaleListItems.announceCartChanges();

	}

	public String getBirthdayDate() {
		return BirthdayDate;
	}

	public void setBirthdayDate(String birthdayDate) {
		BirthdayDate = birthdayDate;
		this.Age = MoleQUtil.getYear2(birthdayDate);
	}

	public boolean haveAgeVerifyItem() {
		boolean result = false;
		for (int i = 0; i < mSaleListItems.getItemCount(); i++) {
			if (mSaleListItems.getItem(i).getAge() > 0) {
				result = true;
				break;
			}
		}
		return result;
	}
	
	public boolean haveServiceItem() {
		boolean result = false;
		for (int i = 0; i < mSaleListItems.getItemCount(); i++) {
			if (mSaleListItems.getItem(i).isServiceItem() && !mSaleListItems.getItem(i).isRefund()) {
				result = true;
				break;
			}
		}
		return result;
	}
	
	public List<SaleListItem> getServiceItemListByID(int printerID) {
		List<SaleListItem> tempList = new ArrayList<SaleListItem>();
		for (int i = 0; i < mSaleListItems.getItemCount(); i++) {
			SaleListItem item = mSaleListItems.getItem(i);
			if (item.isServiceItem() && item.getPrinter_id() == printerID && !item.isRefund()) {
				tempList.add(mSaleListItems.getItem(i));
			}
		}
		return tempList;
	}
	
	public List<SaleListItem> getServiceItemAllList() {
		List<SaleListItem> tempList = new ArrayList<SaleListItem>();
		for (int i = 0; i < mSaleListItems.getItemCount(); i++) {
			SaleListItem item = mSaleListItems.getItem(i);
			if (item.isServiceItem() && !item.isRefund()) {
				tempList.add(mSaleListItems.getItem(i));
			}
		}
		return tempList;
	}
	
	public boolean haveInvalidAgeItem(int age) {
		boolean result = false;
		for (int i = 0; i < mSaleListItems.getItemCount() ; i++) {
			if (mSaleListItems.getItem(i).getAge() > age) {
				result = true;
				break;
			}
		}
		return result;
	}
	
	public boolean haveInvalidWICItem() {
		boolean result = false;
		for (int i = 0; i < mSaleListItems.getItemCount() ; i++) {
			if (!mSaleListItems.getItem(i).isWic()) {
				result = true;
				break;
			}
		}
		return result;
	}
	
	public boolean haveInvalidCVVItem() {
		boolean result = false;
		for (int i = 0; i < mSaleListItems.getItemCount() ; i++) {
			if (!mSaleListItems.getItem(i).isCvv()) {
				result = true;
				break;
			}
		}
		return result;
	}

	public boolean canUseItemDiscount() {
		// TODO Auto-generated method stub
		boolean result = false;
		SaleListItem item = mSaleListItems.getCurrentSelectedItem();
		
		if(item != null){
			ItemType type = item.getItemType();
			if((type == ItemType.REGULAR ||type == ItemType.MULTIPLE_PRICE || type == ItemType.PACKAGE_PRICE) && !item.isRefund()){
				result = true;
			}
		}
		return result;
	}

	public boolean canUseItemCoupon() {
		boolean result = false;
		SaleListItem item = mSaleListItems.getCurrentSelectedItem();
		if (item != null) {
			ItemType type = item.getItemType();
			if ((type == ItemType.REGULAR || type == ItemType.MULTIPLE_PRICE || type == ItemType.PACKAGE_PRICE) && !item.isRefund()) {
				result = true;
			}
		}
		return result;
	}
	
	public boolean canUsePriceChange() {
		boolean result = false;
		SaleListItem item = mSaleListItems.getCurrentSelectedItem();
		if (item != null) {
			ItemType type = item.getItemType();
			if (type == ItemType.REGULAR && item.getInsertType().equals("1000") && !isUseVdrCoupon(item.getVdrCouponBarcode())) {
				result = true;
			}
		}
		return result;
	}
	
	public boolean isUseVdrCoupon(String[] temp){
		
		for (int i = 0; i < temp.length; i++) {
			String str =temp[i]; 
			if(str!=null&&str.length()>0)
			{
				return true;
			}
		}
		return false;
	}

	public double getRefundAmount() {
		double subTotal = 0;
		for (int i = 0; i < mSaleListItems.getItemCount(); i++) {
			if (mSaleListItems.getItem(i).isRefund()) {
				if (mSaleListItems.getItem(i).getItemType() == ItemType.REGULAR ||
					mSaleListItems.getItem(i).getItemType() == ItemType.OPEN_DEPARTMENT ||
					mSaleListItems.getItem(i).getItemType() == ItemType.LIMITED_QTY_PRICE_FIX) {
					subTotal += mSaleListItems.getItem(i).getPrice();
				}
			}
		}
		return BigDecmialTool.round(subTotal, 2);
	}
	
	public int getRefundCount() {
		int count = 0;
		for (int i = 0; i < mSaleListItems.getItemCount(); i++) {
			if (mSaleListItems.getItem(i).isRefund()) {
				if (mSaleListItems.getItem(i).getItemType() == ItemType.REGULAR ||
						mSaleListItems.getItem(i).getItemType() == ItemType.OPEN_DEPARTMENT) {
					count ++;
				}
			}
		}
		return count;
	}

	/************* Create Inventory Files *************/
	public void exportInvFile() {
		if (GlobalInfo.getInstance().isInventory) {
			try {
			
				String action = "";
				for (int i = 0; i < mSaleListItems.mSaleItems.size(); i++) {

					SaleListItem mSaleListItem = mSaleListItems.mSaleItems.get(i);
					if (mSaleListItem.getItemType() == ItemType.REGULAR ||mSaleListItem.getItemType() == ItemType.DISCOUNT_MIX ||mSaleListItem.getItemType() == ItemType.PACKAGE_PRICE 
							|| mSaleListItem.getItemType() == ItemType.PACKAGE_ITEM) {
						int qty = mSaleListItem.getQty();
						if (MoleQUtil.getTransType(TransType).equals("R") || mSaleListItem.isRefund()) {
							qty *= -1;
						}
						ItemSales itemSales = new ItemSales(GlobalInfo.getInstance().storeNo, GlobalInfo.getInstance().stationNo, TransactionNo, trnDate, mSaleListItem.getUpc(), qty, mSaleListItem.getWeight(), GlobalInfo.getInstance().weightUnit, mSaleListItem.getPrice());
						if (action.equals("")) {
							action += itemSales.toMGData("INSERT");
						} else {
							action += "\n" + itemSales.toMGData("INSERT");
						}
					}
				}
				if (!action.trim().equals("")) {
					MGCreateFiles mMGCreateFiles = new MGCreateFiles();
					mMGCreateFiles.createrFile(action, "ITY");// UPDATE,DELETE
					action = "";
				}
			} catch (Exception e) {
				//MessageBox.show(mContext, "Error : " + e.getMessage());
			}

		}
		
	}
}
